package main;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;

public class StanfordWifi implements Source {

	private int period;
	private String trace_table;
	private Connection con;
	private String host;
	private String basename;
	private String username;
	private String password;
	private Statement s;

	public void importData(MySqlConnect mysql) {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection("jdbc:mysql://" + host + "/"
					+ basename, username, password);
			s = con.createStatement();
			String query = "select * from (select id, from_unixtime(time) as time, size, user, ap, app, dir, host from "
					+ this.trace_table
					+ " order by id asc limit 5000) as t order by id asc;";
			long start = System.currentTimeMillis();
			s.execute(query);
			System.out.println(query + "\n t:" + (System.currentTimeMillis()-start)/1000 + "sec");
			ResultSet rs = s.getResultSet();
			ArrayList<Integer> modified = new ArrayList<Integer>();

			while (rs.next()) {
				String[] b = { rs.getString("time"), "msg",
						rs.getString("user"),
						rs.getString("user"),
						rs.getString("user"), "1200" };
				mysql.saveDhcp(b);
				
				String[] a = { rs.getString("time"), rs.getString("user"),
						rs.getString("size"), rs.getString("ap"),
						rs.getString("app"), rs.getString("dir"),
						rs.getString("host") };
				mysql.saveTraffic(a);

				// kolejne agregacje i zapis symulacji dhcp
				// date = a[0]
				// msg = a[1]
				// mac = a[2]
				// host = a[3]
				// ip = a[4]
				// leased = a[5]


				mysql.aggregateGlobalNoPeriod(period, a);
				mysql.aggregateUserNoPeriod(period, a);
				modified.add(rs.getInt("id"));
			}
			query = "delete from " + this.trace_table + " where id>="
					+ Collections.min(modified) + " and id <="
					+ Collections.max(modified) + ";";
			System.out.println(query);
			s.executeUpdate(query);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void setParameters(String[] a, int aggregate_period) {
		this.period = aggregate_period;
		this.host = a[0];
		this.basename = a[1];
		this.username = a[2];
		this.password = a[3];
		this.trace_table = a[4];
	}

}
